import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { 
  NoteDaily, 
  NoteDocument, 
  NoteCategory, 
  NoteQuery,
  PageResponse 
} from '@/types/api'
import { 
  getDailyNotes, 
  getDocumentNotes, 
  getNoteById,
  getRecommendedNotes,
  getHotNotes,
  getNoteCategories,
  getHotTags,
  searchNotes
} from '@/api/note'

export const useNoteStore = defineStore('note', () => {
  // 状态
  const dailyNotes = ref<NoteDaily[]>([])
  const documentNotes = ref<NoteDocument[]>([])
  const recommendedNotes = ref<NoteDaily[]>([])
  const hotNotes = ref<NoteDaily[]>([])
  const currentNote = ref<NoteDaily | NoteDocument | null>(null)
  const categories = ref<NoteCategory[]>([])
  const hotTags = ref<{ name: string; count: number }[]>([])
  const searchResults = ref<(NoteDaily | NoteDocument)[]>([])
  
  // 分页信息
  const dailyPagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
  })
  
  const documentPagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
  })
  
  const searchPagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
  })
  
  // 加载状态
  const isLoading = ref(false)
  const isLoadingRecommended = ref(false)
  const isLoadingHot = ref(false)
  const isLoadingCategories = ref(false)
  const isLoadingTags = ref(false)
  const isSearching = ref(false)

  // 计算属性
  const totalDailyNotes = computed(() => dailyPagination.value.total)
  const totalDocumentNotes = computed(() => documentPagination.value.total)
  const totalSearchResults = computed(() => searchPagination.value.total)

  // 获取日常笔记列表
  const fetchDailyNotes = async (params: NoteQuery = {}) => {
    try {
      isLoading.value = true
      const query = {
        pageNum: dailyPagination.value.pageNum,
        pageSize: dailyPagination.value.pageSize,
        ...params
      }
      
      const response = await getDailyNotes(query)
      dailyNotes.value = response.rows
      dailyPagination.value = {
        pageNum: query.pageNum,
        pageSize: query.pageSize,
        total: response.total
      }
      
      return response
    } catch (error) {
      console.error('Failed to fetch daily notes:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取文档笔记列表
  const fetchDocumentNotes = async (params: NoteQuery = {}) => {
    try {
      isLoading.value = true
      const query = {
        pageNum: documentPagination.value.pageNum,
        pageSize: documentPagination.value.pageSize,
        ...params
      }
      
      const response = await getDocumentNotes(query)
      documentNotes.value = response.rows
      documentPagination.value = {
        pageNum: query.pageNum,
        pageSize: query.pageSize,
        total: response.total
      }
      
      return response
    } catch (error) {
      console.error('Failed to fetch document notes:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取推荐笔记
  const fetchRecommendedNotes = async (limit = 6) => {
    try {
      isLoadingRecommended.value = true
      const notes = await getRecommendedNotes(limit)
      recommendedNotes.value = notes
      return notes
    } catch (error) {
      console.error('Failed to fetch recommended notes:', error)
      throw error
    } finally {
      isLoadingRecommended.value = false
    }
  }

  // 获取热门笔记
  const fetchHotNotes = async (limit = 10) => {
    try {
      isLoadingHot.value = true
      const notes = await getHotNotes(limit)
      hotNotes.value = notes
      return notes
    } catch (error) {
      console.error('Failed to fetch hot notes:', error)
      throw error
    } finally {
      isLoadingHot.value = false
    }
  }

  // 获取笔记详情
  const fetchNoteDetail = async (id: number) => {
    try {
      isLoading.value = true
      const note = await getNoteById(id)
      currentNote.value = note
      return note
    } catch (error) {
      console.error('Failed to fetch note detail:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取笔记分类
  const fetchCategories = async () => {
    try {
      isLoadingCategories.value = true
      const categoryList = await getNoteCategories()
      categories.value = categoryList
      return categoryList
    } catch (error) {
      console.error('Failed to fetch categories:', error)
      throw error
    } finally {
      isLoadingCategories.value = false
    }
  }

  // 获取热门标签
  const fetchHotTags = async (limit = 20) => {
    try {
      isLoadingTags.value = true
      const tags = await getHotTags(limit)
      hotTags.value = tags
      return tags
    } catch (error) {
      console.error('Failed to fetch hot tags:', error)
      throw error
    } finally {
      isLoadingTags.value = false
    }
  }

  // 搜索笔记
  const searchNotesAction = async (keyword: string, params: Omit<NoteQuery, 'keyword'> = {}) => {
    try {
      isSearching.value = true
      const query = {
        keyword,
        pageNum: searchPagination.value.pageNum,
        pageSize: searchPagination.value.pageSize,
        ...params
      }
      
      const response = await searchNotes(query)
      searchResults.value = response.rows
      searchPagination.value = {
        pageNum: query.pageNum,
        pageSize: query.pageSize,
        total: response.total
      }
      
      return response
    } catch (error) {
      console.error('Failed to search notes:', error)
      throw error
    } finally {
      isSearching.value = false
    }
  }

  // 设置日常笔记分页
  const setDailyPagination = (pagination: Partial<typeof dailyPagination.value>) => {
    dailyPagination.value = { ...dailyPagination.value, ...pagination }
  }

  // 设置文档笔记分页
  const setDocumentPagination = (pagination: Partial<typeof documentPagination.value>) => {
    documentPagination.value = { ...documentPagination.value, ...pagination }
  }

  // 设置搜索分页
  const setSearchPagination = (pagination: Partial<typeof searchPagination.value>) => {
    searchPagination.value = { ...searchPagination.value, ...pagination }
  }

  // 清空当前笔记
  const clearCurrentNote = () => {
    currentNote.value = null
  }

  // 清空搜索结果
  const clearSearchResults = () => {
    searchResults.value = []
    searchPagination.value = {
      pageNum: 1,
      pageSize: 10,
      total: 0
    }
  }

  return {
    // 状态
    dailyNotes,
    documentNotes,
    recommendedNotes,
    hotNotes,
    currentNote,
    categories,
    hotTags,
    searchResults,
    dailyPagination,
    documentPagination,
    searchPagination,
    
    // 加载状态
    isLoading,
    isLoadingRecommended,
    isLoadingHot,
    isLoadingCategories,
    isLoadingTags,
    isSearching,
    
    // 计算属性
    totalDailyNotes,
    totalDocumentNotes,
    totalSearchResults,
    
    // 方法
    fetchDailyNotes,
    fetchDocumentNotes,
    fetchRecommendedNotes,
    fetchHotNotes,
    fetchNoteDetail,
    fetchCategories,
    fetchHotTags,
    searchNotesAction,
    setDailyPagination,
    setDocumentPagination,
    setSearchPagination,
    clearCurrentNote,
    clearSearchResults
  }
})